package com.example.library.datasource

import android.util.ArrayMap
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

abstract class RemoteDataSource protected constructor(iNetworkSetting: IRemoteSetting) {
    private val iNetworkSetting: IRemoteSetting

    init {
        this.iNetworkSetting = iNetworkSetting
    }

    companion object {
        private val cacheMap: MutableMap<String, Retrofit?> = ArrayMap<String, Retrofit?>()
    }

    /**
     * 创建 网络请求接口
     */
    fun <T> createService(clazz: Class<T>): T {
        val retrofit: Retrofit = cacheMap[iNetworkSetting.baseUrl] ?: getRetrofitBuilder().build()
        cacheMap[iNetworkSetting.baseUrl] = retrofit
        return retrofit.create<T>(clazz)
    }

    /**
     * 获取 retrofit
     */
    protected open fun getRetrofitBuilder(): Retrofit.Builder {
        return Retrofit.Builder()
            .baseUrl(iNetworkSetting.baseUrl)
            .client(getOkhttpClient())
            .addConverterFactory(GsonConverterFactory.create())
    }

    /**
     * 获取 okhttp
     */
    protected open fun getOkhttpClient(): OkHttpClient {
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
        val interceptorList: List<Interceptor> = getInterceptorList()
        if (interceptorList.isNotEmpty()) {
            for (item in interceptorList) {
                builder.addInterceptor(item)
            }
        }
        val isDebug = iNetworkSetting.isDebug
        if (isDebug) {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            builder.addInterceptor(interceptor)
        }
        return builder.build()
    }


    /**
     * 获取拦截器
     */
    protected open fun getInterceptorList(): List<Interceptor> {
        return listOf()
    }
}